﻿namespace LeadMaster.Controllers
{
  using System;
  using System.Data.Entity;
  using System.Linq;
  using System.Web.Mvc;
  using LeadMaster.DAL;
  using LeadMaster.ViewModels;
  using System.Web.Security;
  using LeadMaster.Helpers;
  using System.Collections.Generic;
  using LeadMaster.Models;
  using System.Data;
  using LeadMaster.Properties;
  using System.Configuration;
  using System.Web;
  using System.IO;
  using System.Text;
  using LeadMaster.Interfaces;
using System.Net;

  [Authorize]
  public class OutsourcerController : Controller
  {

    private DunsmoreContext db = new DunsmoreContext();

      public ActionResult Index()
      {
        ViewModelOutsourcer viewModel = new ViewModelOutsourcer();
        int callCentreID = GetID();
        ViewBag.LeadClient = new SelectList(db.Leads
              .Join(db.PurchaseOrders, a => a.LeadID, b => b.LeadID, (a,b) => new { a,b })
              .Where(m => m.a.LeadID==m.b.LeadID)
              .Where(m => m.b.Visible == true)
              .Where(m => m.a.IntRef != null && m.a.IntRef.Length > 0)
              .Where(m => m.b.Paid == null || m.b.Paid == false)
              .Where(m => m.b.CallCentreID == callCentreID)
              .OrderBy(m => m.a.IntRef)
              .Select(m => new {m.a.LeadID, m.a.IntRef})
              .Distinct()
            , "LeadID", "IntRef");
        viewModel.LeadDate = DateTime.Now;
        viewModel.CallCentreID = callCentreID;
        return View(viewModel);
      }

      [HttpPost]
      public ActionResult Index(ViewModelOutsourcer viewModel)
      {
        return RedirectToAction("FetchLeadBlock", viewModel);
      }

      public ActionResult EnterLeads()
      {
        try
        {
          int callCentreID = GetID();
          var clientList=db.Leads
              .Join(db.PurchaseOrders, a => a.LeadID, b => b.LeadID, (a,b) => new { a,b })
              .Join(db.Surveys, c => c.b.SurveyID, d => d.SurveyID, (c,d) => new { c,d })
              .Where(m => m.c.a.LeadID==m.c.b.LeadID)
              .Where(m => m.c.b.Visible == true)
              .Where(m => m.c.a.IntRef != null && m.c.a.IntRef.Length > 0)
              .Where(m => m.c.b.Paid==null || m.c.b.Paid==false)
              .Where(m => m.c.b.CallCentreID == callCentreID)
              .Where(m => m.c.b.SurveyID == m.d.SurveyID)
              .OrderBy(m => m.c.a.IntRef)
              .Select(m => new {PurchaseOrderID = m.c.b.PurchaseOrderID, IntRef = "PO " + m.c.b.PID + ". " + m.c.a.IntRef + " : " + m.d.Ref})
              .Distinct();
          ViewBag.LeadClient = new SelectList(clientList.OrderBy(m => m.IntRef).Distinct()
              , "PurchaseOrderID", "IntRef");
          ViewBag.CallCentreID = callCentreID;
          return View();
        }
        catch (Exception e)
        {
          ViewBag.ErrorMessage = "Enter Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
          return View("Errormessages");
        }
      }

      [HttpPost]
      public ActionResult EnterLeads(ViewModelSurveys viewModel)
      {
        try
        {
          return RedirectToAction("Survey", new {purchaseOrderID=viewModel.LeadClient });
        }
        catch (Exception e)
        {
          ViewBag.ErrorMessage = "Enter Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
          return View("Errormessages");
        }
      }

      [HttpPost]
      public ActionResult Questionnaire(ViewModelOutsourcer viewModel)
      {
        // check - can we really add a lead and possibly over supply
        int callCentreID = GetID();
        int? LeftToSupply = db.PurchaseOrders
            .Where(m => m.LeadID == viewModel.Leads.LeadID)
            .Where(m => m.Visible == true)
            .Where(m => m.CallCentreID == callCentreID)
            .Where(m => m.Paid==null || m.Paid==false)
            .Select(m => m.Deficit)
            .Sum();
        if (LeftToSupply==null || LeftToSupply==0)
        {
            return View("NoneToSupply");
        }
        try
        {
            int nextBlockID = 0;
            if (db.LeadResults.Where(m => m.LeadID==viewModel.Leads.LeadID).Count()>0)
            {
              nextBlockID = (from l in db.LeadResults select l.BlockId).Max();  
            }
            nextBlockID++;

            foreach (var item in viewModel.LeadQuestions)
            {
              viewModel.LeadResult = new LeadResults();
              viewModel.LeadResult.Question=item.TheQuestion;
              if (item.QuestionType=="L")
              {
                viewModel.LeadResult.Answer = item.TheAnswer=="true" ? "Yes" : "No" ;
              }
              else if (item.QuestionType=="C")
              {
                viewModel.LeadResult.Answer = item.TheAnswer;  
              }
          
              viewModel.LeadResult.LeadID=viewModel.Leads.LeadID;
              viewModel.LeadResult.LeadDate = DateTime.Now;
              viewModel.LeadResult.CallCentreID = viewModel.CallCentreID;
              viewModel.LeadResult.QuestionBlock = viewModel.LeadQuestions.Count();
              viewModel.LeadResult.BlockId = nextBlockID;
              viewModel.LeadResult.LeadStatQuestionsID = item.LeadStatQuestionsID;
              viewModel.LeadResult.LeadGroupQuestionsID = item.LeadGroupQuestionsID;
              viewModel.LeadResult.CompanyRegisteredID = item.CompanyRegisteredID;
              viewModel.LeadResult.CompanyRestrictionsID = item.CompanyRestrictionsID;
              viewModel.LeadResult.CompanySundriesID = item.CompanySundriesID;
              viewModel.LeadResult.DisplayOrder = item.DisplayOrder;
          
              db.LeadResults.Add(viewModel.LeadResult);
            }
            LeadStatus leadStatus = new LeadStatus();
            leadStatus.LeadFlagsID = 1;
            leadStatus.LeadReasonsID = 1;
            leadStatus.LeadID = viewModel.Leads.LeadID;
            leadStatus.BlockID = nextBlockID;
            leadStatus.UserID = (Guid)Membership.GetUser().ProviderUserKey;
           
            leadStatus.LeadDate = DateTime.Now.AddDays(1).ToShortDateString();
            leadStatus.CallCentreID = viewModel.CallCentreID;
            db.LeadStatus.Add(leadStatus);
            db.SaveChanges();
        
            return RedirectToAction("Index");
        }
        catch (Exception e)
        {
            ViewBag.ErrorMessage = "Enter Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
            return View("Errormessages");
        }

      }

      private int GetID()
      {
        Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
        var currentUserName = db.Users.Where(m => m.UserID == currentUser).FirstOrDefault();
        var callCentre = db.CallCentres.Where(m => m.CallCentre == currentUserName.UserName.Substring(0,m.CallCentre.Length)).Select(m =>
                new
                {
                  ID = m.CallCentreID
                });
        int callCentreID = callCentre.FirstOrDefault().ID;
        return callCentreID;
      }

      public void ReturnedLeads()
      {

      }

      public ActionResult ChangeLeadStatus(int id)
      {
 
        LeadResults leadResult = db.LeadResults.Find(id);
        LeadStatus leadStatus = db.LeadStatus.Where(m => m.LeadID == leadResult.LeadID && m.BlockID == leadResult.BlockId).FirstOrDefault();
        if (Roles.GetRolesForUser(User.Identity.Name).Contains(ApplicationRoles.Outsourcer))
        {
            ViewBag.LeadFlagsID = new SelectList(db.LeadFlags.Where(m => m.WithOSQC == true), "LeadFlagsID", "Description");
        }
     
        ViewBag.LeadResultsID = id;
        return PartialView(leadStatus);
      }

      [HttpPost]
      public ActionResult ChangeLeadStatus(LeadStatus leadStatus)
      {
        return RedirectToAction("SaveLeadStatus", leadStatus);
      }

      public ActionResult ReleaseToClient(int id)
      {
        LeadStatus leadStatus = db.LeadStatus.Find(id);
        // check - can we really add a lead and possibly over supply
        int callCentreID = GetID();
        int? LeftToSupply = db.PurchaseOrders
            .Where(m => m.LeadID == leadStatus.LeadID)
            .Where(m => m.Visible == true)
            .Where(m => m.CallCentreID == callCentreID)
            .Where(m => m.Paid==null || m.Paid==false)
            .Select(m => m.Deficit)
            .Sum();
        if (LeftToSupply == null || LeftToSupply == 0)
        {
            return View("NoneToSupply");
        }
        Leads lead = db.Leads.Find(leadStatus.LeadID);
        if (lead.DunsmorePreCheck == true)
        {
          leadStatus.LeadFlagsID = 10;
        }
        else
        {
          leadStatus.LeadFlagsID = 2;
        }
        leadStatus.LeadDate = DateTime.Now.ToShortDateString();
        leadStatus.CallCentreID = GetID();
        int POCallCentreID=leadStatus.CallCentreID??0;
        return RedirectToAction("SaveLeadStatus", leadStatus);
      }

      public ActionResult SaveLeadStatus(LeadStatus leadStatus)
      {
        ViewModelOutsourcer viewModel = new ViewModelOutsourcer();
        db.Entry(leadStatus).State = EntityState.Modified;
        db.SaveChanges();

        // has client asked for email notification ?
        Leads lead = db.Leads.Find(leadStatus.LeadID);
        if (lead.NewLeadAlert == true)
        {
            OracMailMessage mm = new OracMailMessage();
            List<LeadResults> lrs = db.LeadResults.Where(m => m.LeadID == leadStatus.LeadID && m.BlockId == leadStatus.BlockID).ToList();
            List<Contacts> recipients = db.Contacts
                            .Join(db.Companies, a => a.CompanyID, b => b.CompanyID, (a, b) => new { a, b })
                            .Where(m => m.a.CompanyID == m.b.CompanyID)
                            .Where(m => m.a.CompanyID == lead.CompanyID)
                            .Select(m => m.a)
                            .ToList();

            mm.EmailSubject = "A lead has just been uploaded under the reference " + lead.IntRef;

            string LeadDetails = string.Format("{0}", Environment.NewLine);
            LeadDetails += string.Format("Lead Details{0}", Environment.NewLine);
            LeadDetails += string.Format("{0}", Environment.NewLine);
            foreach (var item in lrs)
            {
                if (item.Answer != null)
                {
                    LeadDetails += string.Format("{0} - {1}{2}", item.Question, item.Answer ?? string.Empty, Environment.NewLine);
                    LeadDetails += (item.Question + item.Answer).Length > 30 ? Environment.NewLine : string.Empty;
                }
            }
            LeadDetails += string.Format("{0}", Environment.NewLine);
            LeadDetails += string.Format("{0}This is an automated email from Orac, please do not Reply. Please tell Orac the status of this lead after you have processed it. Thank you.", Environment.NewLine);

            // Send to Dunsmore internal QC
            if (leadStatus.LeadFlagsID==10)
            {
                mm.EmailTo = "sarah.w@dunsmoremarketing.co.uk";
                mm.EmailBody = string.Format("Please can you qualify this lead as soon as possible{0}", Environment.NewLine);
                mm.EmailBody += LeadDetails;
                mm.SendEmail();
            }
            else
            {
                // send to each contact who want notification
                foreach (Contacts contact in recipients)
                {
                    if (contact.Email != null && contact.LLN == true)
                    {
                        mm.EmailTo = contact.Email;
                        mm.EmailBody = string.Format("Hello " + contact.Forename + ", greetings from Orac.{0}", Environment.NewLine);
                        mm.EmailBody += string.Format("Please contact this lead as soon as possible as they have just been qualified as a possible candidate for your scheme.{0}", Environment.NewLine);
                        mm.EmailBody += string.Format("{0}", Environment.NewLine);
                        mm.EmailBody += LeadDetails;
                        mm.SendEmail();
                    }
                }
            }
        }
        
        viewModel.LeadStatus = leadStatus;
        viewModel.Leads = db.Leads.Find(leadStatus.LeadID);
        viewModel.LeadClient = leadStatus.LeadID;
        viewModel.LeadDate = db.LeadResults
            .Where(m => m.LeadID == viewModel.LeadStatus.LeadID && m.BlockId == viewModel.LeadStatus.BlockID)
            .Select(m => m.LeadDate)
            .FirstOrDefault();
        viewModel.CallCentreID = GetID();
        return RedirectToAction("FetchLeadBlock", viewModel);
      }

      public ActionResult ChangeLeadReason(int id)
      {
        LeadResults leadResult = db.LeadResults.Find(id);
        LeadStatus leadStatus = db.LeadStatus.Where(m => m.LeadID==leadResult.LeadID && m.BlockID==leadResult.BlockId).FirstOrDefault();
        if (Roles.GetRolesForUser(User.Identity.Name).Contains(ApplicationRoles.Outsourcer))
        {
          ViewBag.LeadReasons = db.LeadReasons.Where(m => m.OSReasons == true).ToList();
        }
        return PartialView(leadStatus);
      }

      [HttpPost]
      public ActionResult ChangeLeadReason(LeadStatus leadStatus)
      {
          ViewModelOutsourcer viewModel = new ViewModelOutsourcer();

          if (ModelState.IsValid)
          {
              db.Entry(leadStatus).State = EntityState.Modified;
              db.SaveChanges();

              viewModel.LeadStatus = leadStatus;
              viewModel.LeadClient = leadStatus.LeadID;
              viewModel.Leads = db.Leads.Find(leadStatus.LeadID);
              viewModel.LeadDate = db.LeadResults
                .Where(m => m.LeadID == viewModel.LeadStatus.LeadID && m.BlockId == viewModel.LeadStatus.BlockID)
                .Select(m => m.LeadDate)
                .FirstOrDefault();
          }
        return RedirectToAction("FetchLeadBlock", viewModel);
      }

      public ActionResult ChangeOsNote(int id)
      {
        LeadStatus leadStatus = db.LeadStatus.Find(id);
        return PartialView(leadStatus);
      }

      [HttpPost]
      public ActionResult ChangeOsNote(LeadStatus leadStatus)
      {
        ViewModelOutsourcer viewModel = new ViewModelOutsourcer();

        if (ModelState.IsValid)
        {
          LeadStatus ls = db.LeadStatus.Find(leadStatus.LeadStatusID);
          ls.OutsourcerNotes = leadStatus.OutsourcerNotes;
          db.Entry(ls).State = EntityState.Modified;
          db.SaveChanges();

          viewModel.LeadStatus = ls;
          viewModel.LeadClient = ls.LeadID;
          viewModel.Leads = db.Leads.Find(ls.LeadID);
          viewModel.LeadDate = db.LeadResults
            .Where(m => m.LeadID == viewModel.LeadStatus.LeadID && m.BlockId == viewModel.LeadStatus.BlockID)
            .Select(m => m.LeadDate)
            .FirstOrDefault();
        }
        viewModel.CallCentreID = GetID();
        return RedirectToAction("FetchLeadBlock", viewModel);
      }

    public ActionResult ShowLeads(ViewModelOutsourcer viewModel)
      {
        viewModel.Leads = db.Leads.Where(m => m.LeadID == viewModel.LeadClient).FirstOrDefault();
        int id = GetID();
        List<LeadResults> leadResults;
        string selectedDate = viewModel.LeadDate.ToShortDateString();
        if (viewModel.ReturnsOnly==true)
        {
            leadResults = db.LeadResults
                         .Join(db.LeadStatus, a => a.LeadID, b => b.LeadID, (a, b) => new { a, b })
                         .Where(m => m.a.LeadID == m.b.LeadID && m.a.BlockId == m.b.BlockID)
                        .Where(m => m.a.CallCentreID == id)
                        .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
                        .Where(m => m.b.LeadFlagsID==5 || m.b.LeadFlagsID==8)
                        .Where(m => m.b.LeadDate == selectedDate)
                        .OrderByDescending(m => m.b.LeadDate)
                        .OrderBy(m => m.a.BlockId)
                        .Select(m => m.a)
                        .OfType<LeadResults>()
                        .ToList();
        }
        else
        {
            leadResults = db.LeadResults
                         .Join(db.LeadStatus, a => a.LeadID, b => b.LeadID, (a, b) => new { a, b })
                         .Where(m => m.a.LeadID == m.b.LeadID && m.a.BlockId == m.b.BlockID)
                        .Where(m => m.a.CallCentreID == id)
                        .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
                        .Where(m => m.b.LeadDate == selectedDate)
                        .OrderByDescending(m => m.b.LeadDate)
                        .OrderBy(m => m.a.BlockId)
                        .Select(m => m.a)
                        .OfType<LeadResults>()
                        .ToList();
        }
        
        int blockID = 0;
        LeadStatus statusBlock=db.LeadStatus.FirstOrDefault();
        LeadFlags leadFlag=db.LeadFlags.FirstOrDefault();
        LeadReasons leadReason=db.LeadReasons.FirstOrDefault();
        viewModel.FullListLeadResults = new List<ListLeadResults>();
        int totalLeads = 0;
        foreach (LeadResults item in leadResults)
        {
          ListLeadResults listLeadResults=new ListLeadResults();
          listLeadResults.LeadResult = item;
          if (item.BlockId!=blockID)
          {
            statusBlock = db.LeadStatus
                .Where(m => m.LeadID == item.LeadID && m.BlockID == item.BlockId)
                .FirstOrDefault();
            leadFlag = db.LeadFlags.Find(statusBlock.LeadFlagsID);
            leadReason = db.LeadReasons.Find(statusBlock.QCLeadReasonsID);

            totalLeads++;
          }
          blockID = item.BlockId;
          listLeadResults.LeadFlag=leadFlag;
          listLeadResults.LeadReason=leadReason;
          listLeadResults.LeadStatus = statusBlock;
          viewModel.FullListLeadResults.Add(listLeadResults);
        }
        // Title Generation for the table
        viewModel.Titles = new List<string>();
        if (viewModel.FullListLeadResults.Count()>0)
        {
          int questionCounter = 0;
          foreach (var item in leadResults)
          {
              viewModel.Titles.Add(item.Question);
              questionCounter++;
              if (questionCounter == item.QuestionBlock)
              {
                questionCounter = 0;
                break;
              }
          }
        }
        ViewBag.TotalLeads = totalLeads;
        ViewBag.ReturnDate = viewModel.LeadDate.AddDays(4).ToShortDateString();
        return View(viewModel);
      }

    public ActionResult ReturnedLeads(ViewModelOutsourcer viewModel)
    {
      viewModel.Leads = db.Leads.Where(m => m.LeadID == viewModel.LeadClient).FirstOrDefault();
      int id = GetID();
      List<LeadResults> leadResults = db.LeadResults
        .Join(db.LeadStatus, a => a.LeadID, b => b.LeadID, (a, b) => new { a, b })
        .Where(m => m.a.LeadID == m.b.LeadID && m.a.BlockId == m.b.BlockID && m.b.LeadFlag.WithOSQC != null && m.b.LeadFlagsID>2)
        .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
        .Where(m => m.a.CallCentreID == id)
        .Where(m => m.a.LeadDate.Year == viewModel.LeadDate.Year && m.a.LeadDate.Month == viewModel.LeadDate.Month && m.a.LeadDate.Day == viewModel.LeadDate.Day)
        .OrderByDescending(m => m.a.BlockId)
        .ThenBy(m => m.a.DisplayOrder)
        .Select(m => m.a)
        .OfType<LeadResults>()
        .ToList();

      int blockID = 0;
      LeadStatus statusBlock = db.LeadStatus.FirstOrDefault();
      LeadFlags leadFlag = db.LeadFlags.FirstOrDefault();
      LeadReasons leadReason = db.LeadReasons.FirstOrDefault();
      viewModel.FullListLeadResults = new List<ListLeadResults>();
      int totalLeads = 0;
      foreach (LeadResults item in leadResults)
      {
        ListLeadResults listLeadResults = new ListLeadResults();
        listLeadResults.LeadResult = item;
        if (item.BlockId != blockID)
        {
          statusBlock = db.LeadStatus
              .Where(m => m.LeadID == item.LeadID && m.BlockID == item.BlockId)
              .FirstOrDefault();
          leadFlag = db.LeadFlags.Find(statusBlock.LeadFlagsID);
          leadReason = db.LeadReasons.Find(statusBlock.QCLeadReasonsID);

          totalLeads++;
        }
        blockID = item.BlockId;
        listLeadResults.LeadFlag = leadFlag;
        listLeadResults.LeadReason = leadReason;
        listLeadResults.LeadStatus = statusBlock;
        viewModel.FullListLeadResults.Add(listLeadResults);
      }
      // Title Generation for the table
      viewModel.Titles = new List<string>();
      if (viewModel.FullListLeadResults.Count() > 0)
      {
        int questionCounter = 0;
        foreach (var item in leadResults)
        {
          viewModel.Titles.Add(item.Question);
          questionCounter++;
          if (questionCounter == item.QuestionBlock)
          {
            questionCounter = 0;
            break;
          }
        }
      }
      ViewBag.TotalLeads = totalLeads;
      ViewBag.ReturnDate = viewModel.LeadDate.AddDays(4).ToShortDateString();
      return View("FetchLeadBlock",viewModel);
    }

    public ActionResult EditLeads(int leadID, int blockID, string caption="")
    {
      try
      {
        ViewModelOutsourcer viewModel = new ViewModelOutsourcer();
        viewModel.Leads = db.Leads.Where(m => m.LeadID == leadID).FirstOrDefault();
        viewModel.ListCompanyRegistered = db.CompanyRegistered.Where(c => c.CompanyID == viewModel.Leads.CompanyID).ToList();
        viewModel.ListCompanyRestrictions = db.CompanyRestriction.Where(c => c.CompanyID == viewModel.Leads.CompanyID).ToList();
        viewModel.ListCompanySundries = db.CompanySundries.Where(c => c.CompanyID == viewModel.Leads.CompanyID).ToList();
        viewModel.LeadTemplate = db.LeadTemplate.Where(c => c.LeadTemplateID == viewModel.Leads.LeadTemplateID).FirstOrDefault();
        viewModel.ListLeadStat = db.LeadStat.Where(l => l.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
        viewModel.ListLeadGroups = db.LeadGroups.Where(l => l.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
        viewModel.ListStatQuestions = db.LeadStatQuestions.Include(i => i.LeadStat).Where(w => w.LeadStat.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
        viewModel.ListGroupQuestions = db.LeadGroupQuestions.Include(i => i.LeadGroups).Where(w => w.LeadGroups.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
        viewModel.LeadQuestions = new List<questiontype>();
        viewModel.BlockID = blockID;
        List<LeadResults> leadResults = db.LeadResults.Where(m => m.LeadID == leadID && m.BlockId == blockID).ToList();
        int questionRow = 0;
        questiontype newQs;
        int questionOrder = 1;
        while (questionOrder != 99)
        {
          // Static Question Set ?
          if (db.LeadStat.Any(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder))
          {
            LeadStat item = db.LeadStat.Where(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder).FirstOrDefault();
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = string.Empty;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = false;
            newQs.IsQuestionHeader = true;
            newQs.QuestionHeader = item.Title;
            newQs.Notes = item.Notes;
            newQs.DisplayOrder = item.DisplayOrder * 100;
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
            foreach (var statitem in viewModel.ListStatQuestions.Where(m => m.LeadStatID == item.LeadStatID).OrderBy(m => m.DisplayOrder))
            {
              newQs = new questiontype();
              newQs.QuestionRow = questionRow;
              newQs.TheQuestion = statitem.Question;
              newQs.TheAnswer = leadResults.Where(m => m.LeadStatQuestionsID == statitem.LeadStatQuestionsID).Select(m => m.Answer).FirstOrDefault();
              newQs.Mandatory = statitem.Mandatory;
              newQs.QuestionType = statitem.AnswerType;
              newQs.Notes = statitem.Notes;
              newQs.AcceptedAnswerChar = statitem.AcceptedAnswerChar;
              newQs.AcceptedAnswerBool = statitem.AcceptedAnswerBool;
              newQs.AcceptedAnswerIntFrom = statitem.AcceptedAnswerIntFrom;
              newQs.AcceptedAnswerIntTo = statitem.AcceptedAnswerIntTo;
              newQs.LeadStatQuestionsID = statitem.LeadStatQuestionsID;
              newQs.DropDown = statitem.DropDown;
              newQs.DisplayOrder = item.DisplayOrder * 100 + statitem.DisplayOrder;
              viewModel.LeadQuestions.Add(newQs);
              questionRow++;
            }
            questionRow++;
          }
          else if (db.LeadGroups.Any(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder))
          {
            LeadGroups item = db.LeadGroups.Where(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder).FirstOrDefault();
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = string.Empty;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = false;
            newQs.IsQuestionHeader = true;
            newQs.QuestionHeader = item.Title;
            newQs.QualifyingGroup = item.QualifyingGroup;
            newQs.MinMandatoryPrimary = item.MinMandatoryPrimary;
            newQs.MinMandatorySecondary = item.MinMandatorySecondary;
            newQs.LeadGroupsID = item.LeadGroupsID;
            newQs.Notes = item.Notes;
            newQs.DisplayOrder = item.DisplayOrder * 100;
            if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
            {
              newQs.SubHeader = "Two groups here. So we need at least " + item.MinMandatoryPrimary.ToString() + " in this group, and ...";
            }
            else if (item.MinMandatoryPrimary > 0)
            {
              newQs.SubHeader = "We need at least " + item.MinMandatoryPrimary.ToString() + " in this group to qualify.";
            }
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
            // Primary Group
            foreach (var groupitem in viewModel.ListGroupQuestions.Where(m => m.LeadGroupsID == item.LeadGroupsID).Where(m => m.PrimarySecondary == "P").OrderBy(m => m.DisplayOrder))
            {
              newQs = new questiontype();
              newQs.QuestionRow = questionRow;
              newQs.TheQuestion = groupitem.Question;
              newQs.TheAnswer = leadResults.Where(m => m.LeadGroupQuestionsID == groupitem.LeadGroupQuestionsID).Select(m => m.Answer).FirstOrDefault();
              newQs.Mandatory = groupitem.Mandatory;
              newQs.QuestionType = groupitem.AnswerType;
              newQs.Notes = groupitem.Notes;
              newQs.DropDown = groupitem.DropDown;
              newQs.AcceptedAnswerChar = groupitem.AcceptedAnswerChar;
              newQs.AcceptedAnswerBool = groupitem.AcceptedAnswerBool;
              newQs.AcceptedAnswerIntFrom = groupitem.AcceptedAnswerIntFrom;
              newQs.AcceptedAnswerIntTo = groupitem.AcceptedAnswerIntTo;
              newQs.LeadGroupQuestionsID = groupitem.LeadGroupQuestionsID;
              newQs.DropDown = groupitem.DropDown;
              newQs.PrimarySecondary = "P";
              newQs.LeadGroupsID = item.LeadGroupsID;
              newQs.QualifyingGroup = item.QualifyingGroup;
              newQs.DisplayOrder = item.DisplayOrder * 100 + groupitem.DisplayOrder;
              viewModel.LeadQuestions.Add(newQs);
              questionRow++;
            }
            if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
            {
              newQs = new questiontype();
              newQs.QuestionRow = questionRow;
              newQs.TheQuestion = string.Empty;
              newQs.TheAnswer = string.Empty;
              newQs.Mandatory = false;
              newQs.IsQuestionHeader = true;
              newQs.QuestionHeader = item.Title;
              if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
              {
                newQs.SubHeader = "... at least " + item.MinMandatorySecondary.ToString() + " in this group to qualify.";
              }
              viewModel.LeadQuestions.Add(newQs);
              questionRow++;
            }
            // Secondary Group
            foreach (var groupitem in viewModel.ListGroupQuestions.Where(m => m.LeadGroupsID == item.LeadGroupsID).Where(m => m.PrimarySecondary == "S").OrderBy(m => m.DisplayOrder))
            {
              newQs = new questiontype();
              newQs.QuestionRow = questionRow;
              newQs.TheQuestion = groupitem.Question;
              newQs.TheAnswer = leadResults.Where(m => m.LeadGroupQuestionsID == groupitem.LeadGroupQuestionsID).Select(m => m.Answer).FirstOrDefault();
              newQs.Mandatory = groupitem.Mandatory;
              newQs.QuestionType = groupitem.AnswerType;
              newQs.Notes = groupitem.Notes;
              newQs.DropDown = groupitem.DropDown;
              newQs.PrimarySecondary = "S";
              newQs.AcceptedAnswerChar = groupitem.AcceptedAnswerChar;
              newQs.AcceptedAnswerBool = groupitem.AcceptedAnswerBool;
              newQs.AcceptedAnswerIntFrom = groupitem.AcceptedAnswerIntFrom;
              newQs.AcceptedAnswerIntTo = groupitem.AcceptedAnswerIntTo;
              newQs.LeadGroupQuestionsID = groupitem.LeadGroupQuestionsID;
              newQs.LeadGroupsID = item.LeadGroupsID;
              newQs.QualifyingGroup = item.QualifyingGroup;
              newQs.DisplayOrder = item.DisplayOrder * 100 + groupitem.DisplayOrder;
              viewModel.LeadQuestions.Add(newQs);
              questionRow++;
            }
            questionRow++;
          }
          else
          {
            questionOrder = 98;
          }
          questionOrder++;
        }
        foreach (var item in viewModel.ListCompanyRegistered)
        {
          newQs = new questiontype();
          newQs.QuestionRow = questionRow;
          newQs.TheQuestion = item.LeadQuestion;
          newQs.TheAnswer = leadResults.Where(m => m.CompanyRegisteredID == item.CompanyRegisteredID).Select(m => m.Answer).FirstOrDefault();
          newQs.Mandatory = item.MandatoryLeadQuestion;
          newQs.QuestionType = "L";
          newQs.Notes = item.Notes;
          newQs.CompanyRegisteredID = item.CompanyRegisteredID;
          viewModel.LeadQuestions.Add(newQs);
          questionRow++;
        }
        foreach (var item in viewModel.ListCompanyRestrictions)
        {
          newQs = new questiontype();
          newQs.QuestionRow = questionRow;
          newQs.TheQuestion = item.LeadQuestion;
          newQs.TheAnswer = leadResults.Where(m => m.CompanyRestrictionsID == item.CompanyRestrictionsID).Select(m => m.Answer).FirstOrDefault();
          newQs.Mandatory = item.MandatoryLeadQuestion;
          newQs.QuestionType = "L";
          newQs.Notes = item.Notes;
          newQs.CompanyRestrictionsID = item.CompanyRestrictionsID;
          viewModel.LeadQuestions.Add(newQs);
          questionRow++;
        }
        if (viewModel.ListCompanySundries.Count() > 0)
        {
          newQs = new questiontype();
          newQs.QuestionRow = questionRow;
          newQs.TheQuestion = string.Empty;
          newQs.TheAnswer = string.Empty;
          newQs.Mandatory = false;
          newQs.IsQuestionHeader = true;
          newQs.QuestionHeader = "Client Specific Questions";
          viewModel.LeadQuestions.Add(newQs);
          questionRow++;
          foreach (var item in viewModel.ListCompanySundries)
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = item.LeadQuestion;
            newQs.TheAnswer = leadResults.Where(m => m.CompanySundriesID == item.CompanySundriesID).Select(m => m.Answer).FirstOrDefault();
            newQs.Mandatory = item.MandatoryLeadQuestion;
            newQs.QuestionType = "L";
            newQs.CompanySundriesID = item.CompanySundriesID;
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
          }
        }
        viewModel.LeadStatus = db.LeadStatus.Where(m => m.LeadID==leadID && m.BlockID==blockID).FirstOrDefault();
        if (caption!=string.Empty && caption.IndexOf("Dunsmore Notes")!=-1)
        {
            viewModel.LeadStatus.Notes += "\n" + DateTime.Now.ToShortDateString() + ": LEAD HAS BEEN REFRESHED\n";
            viewModel.LeadStatus.LeadDate = DateTime.Now.ToShortDateString();
            viewModel.LeadStatus.LeadFlagsID = 10;
        }
        db.Entry(viewModel.LeadStatus).State = EntityState.Modified;
        db.SaveChanges();
        viewModel.PurchaseOrders = new SelectList(db.PurchaseOrders.Where(m => m.LeadID == viewModel.Leads.LeadID), "PurchaseOrderID", "PID");
        return View("EditQuestionnaire", viewModel);
      }
      catch (Exception e)
      {
        ViewBag.ErrorMessage = "Edit Leads Questionnaire " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
        return View("Errormessages");
      }
    }

    [HttpPost]
    public ActionResult EditQuestionnaire(ViewModelOutsourcer viewModel)
    {
      try
      {
        int nextBlockID = viewModel.BlockID;
        foreach (var item in viewModel.LeadQuestions)
        {
          viewModel.LeadResult = db.LeadResults
            .Where(m => m.LeadID == viewModel.Leads.LeadID)
            .Where(m => m.BlockId == viewModel.BlockID)
            .Where(m => m.Question == item.TheQuestion)
            .FirstOrDefault();
          if (viewModel.LeadResult!=null)
          {
            if (item.QuestionType == "L")
            {
              viewModel.LeadResult.Answer = item.TheAnswer == "true" ? "Yes" : "No";
            }
            else if (item.QuestionType == "C")
            {
              viewModel.LeadResult.Answer = item.TheAnswer;
            }
            else if (item.QuestionType == "I")
            {
              viewModel.LeadResult.Answer = item.TheAnswer;
            }
          }
        }
        db.Entry(viewModel.LeadResult).State = EntityState.Modified;
        int? holdingPurchaseOrderID = viewModel.LeadStatus.PurchaseOrderID;
        viewModel.LeadStatus = db.LeadStatus.Where(m => m.LeadID == viewModel.Leads.LeadID && m.BlockID == viewModel.BlockID).FirstOrDefault();
        if (holdingPurchaseOrderID!=null)
        {
            viewModel.LeadStatus.PurchaseOrderID = holdingPurchaseOrderID;
        }
        viewModel.LeadStatus.LeadFlagsID = 1;
        viewModel.LeadStatus.UserID = (Guid)Membership.GetUser().ProviderUserKey;
        db.Entry(viewModel.LeadStatus).State = EntityState.Modified;

        db.SaveChanges();
        return RedirectToAction("Index");
      }
      catch (Exception e)
      {
        ViewBag.ErrorMessage = "Enter Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
        return View("Errormessages");
      }

    }

    public ActionResult FetchLeadBlock(ViewModelOutsourcer viewModel)
    {
        int id = GetID();
        viewModel.Leads = db.Leads.Where(m => m.LeadID == viewModel.LeadClient).FirstOrDefault();
        var leadDates = from ls in db.LeadStatus
            where ls.LeadID == viewModel.Leads.LeadID
            where ls.CallCentreID == viewModel.CallCentreID
            where viewModel.ReturnsOnly==true ? (ls.LeadFlagsID==5 || ls.LeadFlagsID==8) : (ls.LeadFlag.WithOSQC != null || ls.LeadFlagsID>0)
            select new { ls.LeadDate};


        var lds = (from ld in leadDates.AsEnumerable()
                   select new { leadtimestamp = ld.LeadDate, orderDate = ld.LeadDate.Substring(6, 4) + ld.LeadDate.Substring(3, 2) + ld.LeadDate.Substring(0, 2) })
                            .Distinct();
        ViewBag.LeadID = viewModel.Leads.LeadID;
        ViewBag.CallCentreID = viewModel.CallCentreID;
        ViewBag.ReturnsOnly = viewModel.ReturnsOnly ? 1 : 0;
        List<string> leadtimestamps = lds.OrderByDescending(m => m.orderDate).Select(m => m.leadtimestamp).ToList();
        return View(leadtimestamps);
    }

    public ActionResult ShowLeadsByDate(string leadDate, int id, int indexer, int callCentreID, int returnsOnly)
    {
        int testrecs = 0;
        try
        {
            ViewModelOutsourcer viewModel = new ViewModelOutsourcer();
            viewModel.Leads = db.Leads.Where(m => m.LeadID == id).FirstOrDefault();
            if (false && viewModel.Leads.StreetView == true)
            {
              string companyPostcode = viewModel.Leads.Company.Postcode.Replace(" ", "");
              PostCodes postCodes = db.Postcodes.Where(m => m.Postcode == companyPostcode).FirstOrDefault();
              ViewBag.LatLong = string.Format("{0},{1}", postCodes.lat.ToString(), postCodes.longitude.ToString());
            } 
            leadDate = leadDate.Substring(1, 10);
            List<LeadResults> leadResults;
            if (returnsOnly == 1)
            {
                leadResults = db.LeadResults
                    .Join(db.LeadStatus, a => a.LeadID, b => b.LeadID, (a, b) => new { a, b })
                    .Where(m => m.a.LeadID == m.b.LeadID && m.a.BlockId == m.b.BlockID && (m.b.LeadFlag.WithOSQC != null || m.b.LeadFlagsID == 8))
                    .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
                    .Where(m => m.b.LeadDate == leadDate)
                    .Where(m => m.b.CallCentreID == callCentreID)
                    .Where(m => m.b.LeadFlagsID==5 || m.b.LeadFlagsID==8)
                    .Select(m => m.a)
                    .OfType<LeadResults>()
                    .ToList();
            }
            else
            {
                leadResults = db.LeadResults
                    .Join(db.LeadStatus, a => a.LeadID, b => b.LeadID, (a, b) => new { a, b })
                    .Where(m => m.a.LeadID == m.b.LeadID && m.a.BlockId == m.b.BlockID && (m.b.LeadFlagsID>0))
                    .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
                    .Where(m => m.b.LeadDate == leadDate)
                    .Where(m => m.b.CallCentreID == callCentreID)
                    .Select(m => m.a)
                    .OfType<LeadResults>()
                    .ToList();
            }
            int blockID = 0;
            LeadStatus statusBlock = db.LeadStatus.FirstOrDefault();
            LeadFlags leadFlag = db.LeadFlags.FirstOrDefault();
            LeadReasons leadReason = db.LeadReasons.FirstOrDefault();
            viewModel.FullListLeadResults = new List<ListLeadResults>();
            testrecs = leadResults.Count();
            viewModel.LeadDate = leadResults.LastOrDefault().LeadDate;
            int totalLeads = 0;
            foreach (LeadResults item in leadResults)
            {
                ListLeadResults listLeadResults = new ListLeadResults();
                listLeadResults.LeadResult = item;
                if (item.BlockId != blockID)
                {
                    statusBlock = db.LeadStatus
                        .Where(m => m.LeadID == item.LeadID && m.BlockID == item.BlockId)
                        .FirstOrDefault();
                    leadFlag = db.LeadFlags.Find(statusBlock.LeadFlagsID);
                    if (statusBlock.QCLeadReasonsID!=null && statusBlock.QCLeadReasonsID>1)
                    {
                      leadReason = db.LeadReasons.Find(statusBlock.QCLeadReasonsID);  
                    }
                    else
                    {
                      leadReason = db.LeadReasons.Find(statusBlock.LeadReasonsID);  
                    }
                    
                    totalLeads++;
                }
                blockID = item.BlockId;
                listLeadResults.LeadStatus = statusBlock;
                listLeadResults.LeadFlag = leadFlag;
                listLeadResults.LeadReason = leadReason;

                viewModel.FullListLeadResults.Add(listLeadResults);
            }
            viewModel.Titles = new List<string>();

            if (viewModel.FullListLeadResults.Count() > 0)
            {
                int questionCounter = 0;
                foreach (var item in leadResults)
                {
                    viewModel.Titles.Add(item.Question);
                    questionCounter++;
                    if (questionCounter == item.QuestionBlock)
                    {
                        questionCounter = 0;
                        break;
                    }
                }
            }

            ViewBag.TotalLeads = totalLeads;
            ViewBag.Indexer = indexer;
            return PartialView("PartialShowLeads", viewModel);
        }
        catch (Exception e)
        {
            ViewBag.ErrorMessage = "Showing Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException + " - num of recs=" + testrecs.ToString();
            return View("Errormessages");
        }
    }

    public ActionResult CallCentreStats()
    {
        int callcentreid = GetID();
        return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fCallCentreStats&rs:Command=Render&c=" + callcentreid.ToString());
        //return RedirectToAction("ShowPDF", new { callCentreID = callcentreid, pdfname = pdfName, specificReport = 1 });
    }

    public ActionResult ClientAgentstats()
    {
      int callcentreid = GetID();
      CallCentres callCentre = db.CallCentres.Find(callcentreid);
      string pdfName = callCentre.CallCentre;
      return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fClientAgentStats&rs:Command=Render&c=" + callcentreid.ToString());
      //return RedirectToAction("ShowPDF", new { callCentreID = callcentreid, pdfname = pdfName, specificReport=2 });
    }

    public ActionResult CCstats()
    {
        int callcentreid = GetID();
        return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fCCstats&rs:Command=Render&c=" + callcentreid.ToString());
        //return RedirectToAction("ShowPDF", new { callCentreID = callcentreid, pdfname = pdfName, specificReport = 1 });
    }

    public ActionResult ReturnStats()
    {
        int callcentreid = GetID();
        return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fReturnAnalysisByCallCentre&rs:Command=Render&c=" + callcentreid.ToString());
        //return RedirectToAction("ShowPDF", new { callCentreID = callcentreid, pdfname = pdfName, specificReport = 1 });
    }

    public ActionResult PurchaseOrderReport(string pid)
    {
        int callcentreid = GetID();
        return RedirectToAction("ShowPDF", new { callCentreID = callcentreid, pdfname = "PurchaseOrder_"+pid, specificReport = 3 });
    }

    [System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    public FileStreamResult ShowPDF(string callCentreID="1", string pdfname="test", int specificReport=1, string pid="")
    {
      try
      {
      // Create a new proxy to the web service
      rsExecService.ReportExecutionService rsExec = new rsExecService.ReportExecutionService();
      // Authenticate to the web service using windows credentials
      rsExec.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["UserID"], ConfigurationManager.AppSettings["Pwd"]);
      // Load the selected report
      switch (specificReport)
      {
        case 1:
          rsExec.LoadReport("/dunsmore/CallCentreStats", null);
          break;
        case 2:
          rsExec.LoadReport("/dunsmore/ClientAgentStats", null);
          break;
        case 3:
          rsExec.LoadReport("/dunsmore/PurchaseOrder", null);
          break;
        default:
          break;
      }
      

      // Prepare Render arguments
      string encoding = String.Empty;
      string mimeType = String.Empty;
      string extension = String.Empty;
      rsExecService.Warning[] warnings = null;
      string[] streamIDs = null;

      // Prepare report parameters.
      rsExecService.ParameterValue[] parameters = new rsExecService.ParameterValue[1];
      parameters[0] = new rsExecService.ParameterValue();
      parameters[0].Value = callCentreID; 
      parameters[0].Name = "c";
      if (specificReport==3)
      {
        parameters[1] = new rsExecService.ParameterValue();
        parameters[1].Value = pid; 
        parameters[1].Name = "c";
      }

      // Set the parameters for the report needed.
      rsExec.SetExecutionParameters(parameters, "en-us");

      //Render the report to a byte[]
      Byte[] byteInfo = rsExec.Render("PDF", null, out extension, out encoding, out mimeType, out warnings, out streamIDs);

      // Return the report as a file stream
      System.IO.MemoryStream ms = new System.IO.MemoryStream();
      ms.Write(byteInfo, 0, byteInfo.Length);
      ms.Position = 0;

      HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + pdfname + ".pdf");

      return new FileStreamResult(ms, ConfigurationManager.AppSettings["ReportName"]);
      }
      catch (Exception e)
      {
        using (var ms=new MemoryStream())
        {
          using (StreamWriter sw = new StreamWriter(ms, Encoding.Unicode)) {
                sw.WriteLine("Enter Leads " + e.LineNumber().ToString() + " : " + e.Message);
            }
          return new FileStreamResult(ms, "application/text");
        }
      }

    }

    public ActionResult LoadingCapacity()
    {
      try
      {
      int callCentreID = GetID();
      
      LoadingCapacity loadingCapacity = db.LoadingCapacity.Where(m => m.CallCentreID == callCentreID).FirstOrDefault();
      
      DateTime weekBeginning=DateTime.Now;
      if (loadingCapacity == null)
      {
        weekBeginning = DateTime.Now.AddDays(8 - (int)DateTime.Now.DayOfWeek);
      }
      else 
      {
        weekBeginning = db.LoadingCapacity.Where(m => m.CallCentreID == callCentreID).OrderByDescending(m => m.WeekBeginning).Select(m => m.WeekBeginning).FirstOrDefault();
        weekBeginning = weekBeginning.AddDays(7);
      }
      if (loadingCapacity == null || weekBeginning < DateTime.Now.AddDays(49))
      {
        for (int i = 0; i < 8; i++)
        {
          loadingCapacity = new LoadingCapacity();
          loadingCapacity.CallCentreID = callCentreID;
          loadingCapacity.WeekBeginning = weekBeginning;
          db.LoadingCapacity.Add(loadingCapacity);
          weekBeginning = weekBeginning.AddDays(7);
        }
      }
      db.SaveChanges();

      List < LoadingCapacity > listLoadingCapacity= db.LoadingCapacity.Where(m => m.CallCentreID == callCentreID).ToList();

      return View(listLoadingCapacity);
      }
      catch (Exception e)
      {
        ViewBag.ErrorMessage = "Loading Capacity " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
        return View("Errormessages");
      }
    }

    [HttpPost]
    public ActionResult LoadingCapacity(List<LoadingCapacity> listLoadingCapacity)
    {
      foreach (var item in listLoadingCapacity)
      {
        LoadingCapacity lC = db.LoadingCapacity.Find(item.LoadingCapacityID);
        lC.Capacity = item.Capacity;
        db.Entry(lC).State = EntityState.Modified;
      }
      db.SaveChanges();
      return RedirectToAction("Index","Home");
    }

    public string CheckDuplicate(string telephoneNumber)
    {
        telephoneNumber = telephoneNumber.Replace(" ", "");
        int telephoneRecs = db.LeadResults.Where(m => m.Question.ToLower().IndexOf("landline")!=-1 && m.Answer.Replace(" ", "") == telephoneNumber).Count();
            
        if (telephoneRecs>0)
        {
            return "Regret to inform you that we already have this number in the system - this must be a duplicate";
        }
        else
        {
            // Check number format by pattern matching
            if (telephoneNumber.Trim().Length<10)
            {
                return "Regret to inform you that this number appears to be invalid.";
            }
            return string.Empty;
        }
    }

    public string CheckPostcode(string postCode, string leadID)
    {
      if (postCode!=null)
      {
        try
        {
          postCode = postCode.Replace(" ", string.Empty);
          string AlphaPostCode = string.Empty;
          char[] postcodeArray = postCode.ToCharArray();
          foreach (var item in postcodeArray)
          {
            if (char.IsLetter(item))
            {
              AlphaPostCode += item.ToString();
            }
            else
            {
              break;
            }
          }

          string[] Territory = db.Leads.Find(Convert.ToInt16(leadID)).Territory.Split(',');

          if (Array.IndexOf(Territory,AlphaPostCode.ToUpper()) < 0)
          {
            foreach (var item in postcodeArray)
            {
              if (char.IsNumber(item))
              {
                AlphaPostCode += item.ToString();
              }
            }
            foreach (var item in Territory)
            {
              if (item.Any(char.IsDigit) && AlphaPostCode.Substring(0,item.Length).ToUpper()==item)
              {
                return string.Empty;
              }
            }
          }
          else
          {
            return string.Empty;
          }
      }
      catch (Exception)
      {
        return "OutOfTerritory";
      }
      }
      return "OutOfTerritory";
    }

    public static string StreetviewLatLong(int leadStatusID)
    {
      DunsmoreContext db = new DunsmoreContext();
      LeadStatus leadStatus = db.LeadStatus.Find(leadStatusID);
      string postCode = db.LeadResults
          .Where(m => m.LeadID == leadStatus.LeadID && m.BlockId == leadStatus.BlockID && m.Question == "Postcode")
          .Select(m => m.Answer)
          .FirstOrDefault();
      PostCodes postCodes = db.Postcodes.Where(m => m.Postcode == postCode.Replace(" ", "")).FirstOrDefault();
      string returnString = postCodes.lat.ToString() + "," + postCodes.longitude.ToString();
      return returnString;
    }

    public static string StreetviewPostcode(int leadStatusID)
    {
      DunsmoreContext db = new DunsmoreContext();
      LeadStatus leadStatus = db.LeadStatus.Find(leadStatusID);
      string postCode = db.LeadResults
          .Where(m => m.LeadID == leadStatus.LeadID && m.BlockId == leadStatus.BlockID && m.Question == "Postcode")
          .Select(m => m.Answer)
          .FirstOrDefault();
      PostCodes postCodes = db.Postcodes.Where(m => m.Postcode == postCode.Replace(" ", "")).FirstOrDefault();
      string returnString = postCode;
      return returnString;
    }

    public ViewModelOutsourcer ProcessQuestionnaire(ViewModelOutsourcer viewModel, bool preview=false)
    {
      int callCentreID=0;
      if (viewModel.PreviewMode==false)
      {
        callCentreID=GetID();
      }

      if (!preview)
      {
        viewModel.Leads = db.Leads.Where(m => m.LeadID == viewModel.LeadClient).FirstOrDefault();  
      }
      
      if (false && viewModel.Leads.StreetView == true)
      {
        string companyPostcode = viewModel.Leads.Company.Postcode.Replace(" ", "");
        PostCodes postCode = db.Postcodes.Where(m => m.Postcode == companyPostcode).FirstOrDefault();
        ViewBag.LatLong = string.Format("{0},{1}", postCode.lat.ToString(), postCode.longitude.ToString());
      }

      if (viewModel.PreviewMode == false)
      {
        ViewBag.LeftToSupply = db.PurchaseOrders
          .Where(m => m.LeadID == viewModel.LeadClient)
          .Where(m => m.Visible == true)
          .Where(m => m.CallCentreID == callCentreID)
          .Where(m => m.Paid == null || m.Paid == false)
          .Select(m => m.Deficit).Sum().ToString();
      }
      else
      {
        ViewBag.LeftToSupply = 0;
      }
      if (viewModel.Leads!=null && viewModel.Leads.CreditBased == true)
      {
        ViewBag.LeftToSupply += " credits to supply.";
      }
      else
      {
        ViewBag.LeftToSupply += " leads to supply.";
      }

      viewModel.LeadTemplate = db.LeadTemplate.Where(c => c.LeadTemplateID == viewModel.Leads.LeadTemplateID).FirstOrDefault();
      viewModel.ListLeadStat = db.LeadStat.Where(l => l.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
      viewModel.ListLeadGroups = db.LeadGroups.Where(l => l.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
      viewModel.ListStatQuestions = db.LeadStatQuestions.Include(i => i.LeadStat).Where(w => w.LeadStat.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
      viewModel.ListGroupQuestions = db.LeadGroupQuestions.Include(i => i.LeadGroups).Where(w => w.LeadGroups.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
      viewModel.LeadQuestions = new List<questiontype>();
      int questionRow = 0;
      questiontype newQs;
      int questionOrder = 1;
      while (questionOrder != 99)
      {
        // Static Question Set ?
        if (db.LeadStat.Any(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder))
        {
          LeadStat item = db.LeadStat.Where(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder).FirstOrDefault();
          newQs = new questiontype();
          newQs.QuestionRow = questionRow;
          newQs.TheQuestion = string.Empty;
          newQs.TheAnswer = string.Empty;
          newQs.Mandatory = false;
          newQs.IsQuestionHeader = true;
          newQs.QuestionHeader = item.Title;
          newQs.Notes = item.Notes;
          newQs.DisplayOrder = item.DisplayOrder * 100;
          viewModel.LeadQuestions.Add(newQs);
          questionRow++;
          foreach (var statitem in viewModel.ListStatQuestions.Where(m => m.LeadStatID == item.LeadStatID).OrderBy(m => m.DisplayOrder))
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = statitem.Question;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = statitem.Mandatory;
            newQs.QuestionType = statitem.AnswerType;
            newQs.Notes = statitem.Notes;
            newQs.AcceptedAnswerChar = statitem.AcceptedAnswerChar;
            newQs.AcceptedAnswerBool = statitem.AcceptedAnswerBool;
            newQs.AcceptedAnswerIntFrom = statitem.AcceptedAnswerIntFrom;
            newQs.AcceptedAnswerIntTo = statitem.AcceptedAnswerIntTo;
            newQs.LeadStatQuestionsID = statitem.LeadStatQuestionsID;
            newQs.DropDown = statitem.DropDown;
            newQs.DisplayOrder = item.DisplayOrder * 100 + statitem.DisplayOrder;
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
          }
          questionRow++;
        }
        else if (db.LeadGroups.Any(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder))
        {
          LeadGroups item = db.LeadGroups.Where(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder).FirstOrDefault();
          newQs = new questiontype();
          newQs.QuestionRow = questionRow;
          newQs.TheQuestion = string.Empty;
          newQs.TheAnswer = string.Empty;
          newQs.Mandatory = false;
          newQs.IsQuestionHeader = true;
          newQs.QuestionHeader = item.Title;
          newQs.QualifyingGroup = item.QualifyingGroup;
          newQs.MinMandatoryPrimary = item.MinMandatoryPrimary;
          newQs.MinMandatorySecondary = item.MinMandatorySecondary;
          newQs.LeadGroupsID = item.LeadGroupsID;
          newQs.Notes = item.Notes;
          newQs.DisplayOrder = item.DisplayOrder * 100;
          if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
          {
            newQs.SubHeader = "Two groups here. So we need at least " + item.MinMandatoryPrimary.ToString() + " in this group, and ...";
          }
          else if (item.MinMandatoryPrimary > 0)
          {
            newQs.SubHeader = "We need at least " + item.MinMandatoryPrimary.ToString() + " in this group to qualify.";
          }
          viewModel.LeadQuestions.Add(newQs);
          questionRow++;
          // Primary Group
          foreach (var groupitem in viewModel.ListGroupQuestions.Where(m => m.LeadGroupsID == item.LeadGroupsID).Where(m => m.PrimarySecondary == "P").OrderBy(m => m.DisplayOrder))
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = groupitem.Question;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = groupitem.Mandatory;
            newQs.QuestionType = groupitem.AnswerType;
            newQs.Notes = groupitem.Notes;
            newQs.DropDown = groupitem.DropDown;
            newQs.AcceptedAnswerChar = groupitem.AcceptedAnswerChar;
            newQs.AcceptedAnswerBool = groupitem.AcceptedAnswerBool;
            newQs.AcceptedAnswerIntFrom = groupitem.AcceptedAnswerIntFrom;
            newQs.AcceptedAnswerIntTo = groupitem.AcceptedAnswerIntTo;
            newQs.LeadGroupQuestionsID = groupitem.LeadGroupQuestionsID;
            newQs.DropDown = groupitem.DropDown;
            newQs.PrimarySecondary = "P";
            newQs.LeadGroupsID = item.LeadGroupsID;
            newQs.QualifyingGroup = item.QualifyingGroup;
            newQs.DisplayOrder = item.DisplayOrder * 100 + groupitem.DisplayOrder;
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
          }
          if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = string.Empty;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = false;
            newQs.IsQuestionHeader = true;
            newQs.QuestionHeader = item.Title;
            if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
            {
              newQs.SubHeader = "... at least " + item.MinMandatorySecondary.ToString() + " in this group to qualify.";
            }
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
          }
          // Secondary Group
          foreach (var groupitem in viewModel.ListGroupQuestions.Where(m => m.LeadGroupsID == item.LeadGroupsID).Where(m => m.PrimarySecondary == "S").OrderBy(m => m.DisplayOrder))
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = groupitem.Question;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = groupitem.Mandatory;
            newQs.QuestionType = groupitem.AnswerType;
            newQs.Notes = groupitem.Notes;
            newQs.DropDown = groupitem.DropDown;
            newQs.PrimarySecondary = "S";
            newQs.AcceptedAnswerChar = groupitem.AcceptedAnswerChar;
            newQs.AcceptedAnswerBool = groupitem.AcceptedAnswerBool;
            newQs.AcceptedAnswerIntFrom = groupitem.AcceptedAnswerIntFrom;
            newQs.AcceptedAnswerIntTo = groupitem.AcceptedAnswerIntTo;
            newQs.LeadGroupQuestionsID = groupitem.LeadGroupQuestionsID;
            newQs.LeadGroupsID = item.LeadGroupsID;
            newQs.QualifyingGroup = item.QualifyingGroup;
            newQs.DisplayOrder = item.DisplayOrder * 100 + groupitem.DisplayOrder;
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
          }
          questionRow++;
        }
        else
        {
          questionOrder = 98;
        }
        questionOrder++;
      }
      

      return viewModel;
    }

    public ActionResult StartSurvey(int surveyID, int purchaseOrderID)
    {
      Maintenance.inMaintenance = true;
      ViewModelSurveys ViewModel = new ViewModelSurveys();
      ViewModel.Surveys = db.Surveys.Find(surveyID);
      ViewModel.LeadTemplate = db.LeadTemplate.Find(ViewModel.Surveys.LeadTemplateID);
      ViewModel.LeadStat = db.LeadStat.Where(m => m.LeadTemplateID == ViewModel.Surveys.LeadTemplateID).OrderBy(m => m.QuestionOrder).FirstOrDefault();
      ViewModel.LeadStatQuestions = db.LeadStatQuestions.Where(m => m.LeadStatID == ViewModel.LeadStat.LeadStatID).FirstOrDefault();
      ViewModel.PurchaseOrderID = purchaseOrderID;
      ViewBag.StartOfSurvey = true;
      ViewModel.StartFlag = true;
      return View(ViewModel);
    }

    [HttpPost]
    public ActionResult StartSurvey(ViewModelSurveys viewModel)
    {
      return RedirectToAction("Survey", new {surveyID=viewModel.Surveys.SurveyID , purchaseOrderID=viewModel.PurchaseOrderID, leadID=viewModel.LeadID});
    }


    public ActionResult EnterSurvey(Guid userid, string Title = "", string Firstname = "", string Surname = "", string HouseNum = "", string Street = "", string Town = "", string County = "", string Postcode = "", string Landline = "", string Mobile = "", string Email = "", string Agent = "")
    {
      try
      {
        if (db.CallCentres.Where(m => m.LogOn==userid).First()==null)
        {
          return RedirectToAction("Home", "Account");
        }
        int callCentreID = db.CallCentres.Where(m => m.LogOn == userid).First().CallCentreID;
        var clientList = db.Leads
            .Join(db.PurchaseOrders, a => a.LeadID, b => b.LeadID, (a, b) => new { a, b })
            .Join(db.Surveys, c => c.b.SurveyID, d => d.SurveyID, (c, d) => new { c, d })
            .Where(m => m.c.a.LeadID == m.c.b.LeadID)
            .Where(m => m.c.b.Visible == true)
            .Where(m => m.c.a.IntRef != null && m.c.a.IntRef.Length > 0)
            .Where(m => m.c.b.Paid == null || m.c.b.Paid == false)
            .Where(m => m.c.b.CallCentreID == callCentreID)
            .Where(m => m.c.b.SurveyID == m.d.SurveyID)
            .OrderBy(m => m.c.a.IntRef)
            .Select(m => new { SurveyID = m.c.b.SurveyID, Ref = m.d.LeadTemplate.Title })
            .Distinct();
        ViewBag.surveyID = new SelectList(clientList.OrderBy(m => m.Ref).Distinct()
            , "SurveyID", "Ref");
        ViewBag.CallCentreID = callCentreID;
        ViewModelSurveys ViewModel = new ViewModelSurveys();
        ViewModel.UserID = userid;
        ViewModel.Person = new Person();
        if (Title == "")
        {
          ViewModel.Person.Title = db.Salutations.OrderBy(m => m.SalutationID).First().Salutation;
        }
        else
        {
          ViewModel.Person.Title = BespokeFunctions.Proper(Title);
        }
        ViewModel.Person.Forename = BespokeFunctions.Proper(Firstname);
        ViewModel.Person.Surname = BespokeFunctions.Proper(Surname);
        ViewModel.Person.HouseNum = BespokeFunctions.Proper(HouseNum);
        ViewModel.Person.Address1 = BespokeFunctions.Proper(Street);
        ViewModel.Person.TownCity = BespokeFunctions.Proper(Town);
        ViewModel.Person.County = BespokeFunctions.Proper(County);
        ViewModel.Person.Postcode = Postcode.ToUpper();
        ViewModel.Person.Telephone = "0" + Landline;
        ViewModel.Person.Mobile = "0" + Mobile;
        ViewModel.Person.Email = Email.ToLower();
        ViewModel.CallCentreID = callCentreID;
        ViewModel.Agent = Agent;
        // check for salutation in forename
        foreach (var item in db.Salutations)
        {
          if (Firstname.Length>item.Salutation.Length && Firstname.ToLower().IndexOf(item.Salutation.ToLower())>=0)
          {
            ViewBag.fnMessage = "There appears to be a Salutation in the First Name.";
            break;

          }
        }

        ViewBag.Title = new SelectList(db.Salutations, "Salutation", "Salutation",ViewModel.Person.Title);
        ViewBag.County = new SelectList(db.Counties.OrderBy(m => m.CountryID).ThenBy(m => m.County), "County", "County", ViewModel.Person.County);
        ViewBag.Country = new SelectList(db.Countries, "Country", "Country");
        if (db.LeadResults.Count() == 0)
        {
          ViewModel.BlockID = 0;
        }
        else
        {
          ViewModel.BlockID = db.LeadStatus.Max(m => m.BlockID);
        }
        ViewModel.BlockID++;
        LeadStatus leadStatus = new LeadStatus();
        leadStatus.LeadFlagsID = 1;
        leadStatus.LeadReasonsID = 1;
        leadStatus.DunsmorePreCheck = true;
        leadStatus.CallCentreID = ViewModel.CallCentreID;
        leadStatus.BlockID = ViewModel.BlockID;
        db.LeadStatus.Add(leadStatus);
        db.SaveChanges();
        ViewModel.LeadStatusID = leadStatus.LeadStatusID;
        return View(ViewModel);
      }
      catch (Exception e)
      {
        ViewBag.ErrorMessage = "Enter Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException + 
          ". URL Parameters received - Title : " + Title + ", Firstname : " + Firstname + ", Surname : " + Surname + ", HouseNum : " + HouseNum + ", Street : " + 
            Street + ", Town : " + Town + ", County : " + County + ", Postcode : " + Postcode + ", Landline : " + Landline + ", Mobile : " + Mobile + ", Email : " + Email + ", Agent : " + Agent ;
        return View("Errormessages");
      }
    }

    [HttpPost]
    public ActionResult EnterSurvey(ViewModelSurveys viewModel,int purchaseOrderID = 0, int surveyID = 0, string Title="", string County="", string Country="")
    {
      int leadID = 0;

      if (purchaseOrderID != 0)
      {
        PurchaseOrders PO = db.PurchaseOrders.Find(purchaseOrderID);
        surveyID = PO.SurveyID ?? 0;
        leadID = PO.LeadID;
      }
      viewModel.Surveys = db.Surveys.Find(surveyID);
      viewModel.LeadTemplate = db.LeadTemplate.Find(viewModel.Surveys.LeadTemplateID);
      viewModel.LeadStat = db.LeadStat.Where(m => m.LeadTemplateID == viewModel.Surveys.LeadTemplateID).OrderBy(m => m.QuestionOrder).FirstOrDefault();
      viewModel.LeadStatQuestions = db.LeadStatQuestions.Where(m => m.LeadStatID == viewModel.LeadStat.LeadStatID).FirstOrDefault();
      viewModel.StartFlag = false;
      SurveyContacts surveyContacts = new SurveyContacts();

      if (purchaseOrderID == 0)
      {
        // new survey - store contact information
        surveyContacts.LeadStatusID = viewModel.LeadStatusID;
        surveyContacts.Title = Title;
        surveyContacts.Forename = viewModel.Person.Forename;
        surveyContacts.Surname = viewModel.Person.Surname;
        surveyContacts.Address1 = viewModel.Person.HouseNum + ' ' + viewModel.Person.Address1;
        surveyContacts.TownCity = viewModel.Person.TownCity;
        surveyContacts.County = County;
        surveyContacts.PostCode = viewModel.Person.Postcode;
        surveyContacts.Telephone = viewModel.Person.Telephone;
        surveyContacts.Mobile = viewModel.Person.Mobile;
        surveyContacts.Email = viewModel.Person.Email ?? "";
        surveyContacts.Country = Country;
        db.SurveyContacts.Add(surveyContacts);
      }
      db.SaveChanges();
      viewModel.LeadResults = new LeadResults();
      viewModel.LeadResults.BlockId = viewModel.BlockID;
      viewModel.LeadResults.Question = viewModel.LeadStatQuestions.Question;
      viewModel.LeadResults.LeadStatQuestionsID = viewModel.LeadStatQuestions.LeadStatQuestionsID;
      viewModel.LeadResults.Question = viewModel.LeadStatQuestions.Question;
      viewModel.LeadStatQuestionID = viewModel.LeadStatQuestions.LeadStatQuestionsID;

      viewModel.TotalQuestionCount = db.PurchaseOrders
                .Where(m => m.CallCentreID == viewModel.CallCentreID)
                .Where(m => m.Visible == true)
                .Where(m => m.Deficit > 0)
                .Select(m => m.Survey.ListSurveyMappings.Count())
                .Sum(); 
      
      viewModel.QuestionNumber = 1;
      viewModel.SurveyContact = db.SurveyContacts.Where(m => m.LeadStatusID == viewModel.LeadStatusID).FirstOrDefault();
      viewModel.JumpToEnd = false;
      return View("Survey", viewModel);
    }


    public ActionResult Survey( Person person, int purchaseOrderID=0 , int surveyID=0)
    {
      ViewModelSurveys viewModel = new ViewModelSurveys();
      return View("Survey", viewModel);
    }

    [HttpPost]
    public ActionResult Survey(ViewModelSurveys viewModel)
    {
        viewModel.LeadResults.LeadStatQuestionsID = viewModel.LeadStatQuestionID;
        viewModel.LeadResults.LeadDate = DateTime.Now;
        viewModel.LeadResults.CallCentreID = viewModel.CallCentreID;
        viewModel.LeadResults.BlockId = viewModel.BlockID;
        viewModel.LeadResults.Question = db.LeadStatQuestions.Find(viewModel.LeadStatQuestionID).Question;
        db.LeadResults.Add(viewModel.LeadResults);
        db.SaveChanges();
        // next question
        viewModel.LeadStatQuestions = db.LeadStatQuestions.Find(viewModel.LeadStatQuestionID);
        viewModel.LeadStat = db.LeadStat.Find(viewModel.LeadStatQuestions.LeadStatID);
        viewModel.LeadTemplate = db.LeadTemplate.Find(viewModel.LeadStat.LeadTemplateID);
        int displayOrder=viewModel.LeadStatQuestions.DisplayOrder;
        displayOrder++;
        int questionOrder=viewModel.LeadStat.QuestionOrder??0 ;
        questionOrder++;
        bool endOfSurvey=false;
        viewModel.LeadStatQuestions=db.LeadStatQuestions.Where(m => m.LeadStatID==viewModel.LeadStat.LeadStatID && m.DisplayOrder>=displayOrder).OrderBy(m => m.DisplayOrder).FirstOrDefault() ;
        while (db.PurchaseOrders
          .Where(m => m.CallCentreID==viewModel.CallCentreID)
          .Where(m => m.Visible==true)  
          .Where(m => m.Deficit>0)
          .Select(m => m.Survey.ListSurveyMappings)
          .Count()==0)
        {
          displayOrder++;
          viewModel.LeadStatQuestions = db.LeadStatQuestions.Where(m => m.LeadStatID == viewModel.LeadStat.LeadStatID && m.DisplayOrder >= displayOrder).OrderBy(m => m.DisplayOrder).FirstOrDefault();
        }
        // get current mappings
        GenericRepository gr=new GenericRepository();
        viewModel.dtMappings = gr.CurrentMappings(viewModel.BlockID,viewModel.LeadTemplate.LeadTemplateID, viewModel.CallCentreID);
        if (viewModel.LeadStatQuestions == null)
	      {
          displayOrder=1;
		      // next Lead Stat Section
          LeadStat ls=db.LeadStat.Where(m => m.LeadTemplateID==viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder==questionOrder).FirstOrDefault();
          if (ls==null)
	        {
		        // we have got to the end of the question set
            endOfSurvey=true;
	        }
          else
          {
            viewModel.LeadStatQuestions = db.LeadStatQuestions.Where(m => m.LeadStatID == ls.LeadStatID).OrderBy(m => m.DisplayOrder).FirstOrDefault();
          }
      	}
        if (endOfSurvey==false && viewModel.JumpToEnd==false)
	      {
          viewModel.LeadResults = new LeadResults();
          viewModel.LeadResults.BlockId=viewModel.BlockID;
          viewModel.LeadResults.Question = viewModel.LeadStatQuestions.Question;
          viewModel.LeadResults.LeadStatQuestionsID = viewModel.LeadStatQuestions.LeadStatQuestionsID;
          viewModel.LeadResults.Answer = "";
          viewModel.LeadStatQuestionID = viewModel.LeadStatQuestions.LeadStatQuestionsID;
          viewModel.TotalQuestionCount = db.PurchaseOrders
          .Where(m => m.CallCentreID == viewModel.CallCentreID)
          .Where(m => m.Visible == true)
          .Where(m => m.Deficit > 0)
          .Select(m => m.Survey.ListSurveyMappings.Count())
          .Sum(); 
        }
        else
        {
          List<LeadResults> listLeadResults = db.LeadResults.Where(m => m.BlockId == viewModel.BlockID).OrderBy(m => m.LeadResultsID).ToList();
          DateTime timeSlots=listLeadResults.FirstOrDefault().LeadDate;
          decimal slotTime = 0m;
          foreach (var item in listLeadResults)
	        {
            slotTime += (decimal)((item.LeadDate - timeSlots).TotalMilliseconds)/1000;
            item.StartSec = slotTime;
            db.Entry(item).State = EntityState.Modified;
            timeSlots = item.LeadDate;
	        }
          db.SaveChanges();
          return RedirectToAction("CompleteSurvey", new { blockID = viewModel.BlockID, agent = viewModel.Agent, cc=viewModel.CallCentreID });
        }
        viewModel.QuestionNumber++;
        return View("Survey", viewModel);
    }

    public ActionResult CompleteSurvey(int blockID, string agent, int cc)
    {
      Guid ccLogon = db.CallCentres.Find(cc).LogOn;
      SurveyCompletion surveyCompletion = new SurveyCompletion(blockID,agent,ccLogon);

      return View(surveyCompletion);
    }

    [HttpPost]
    public ActionResult CompleteSurvey (SurveyCompletion surveyCompletion)
    {
      db.SurveyCompletion.Add(surveyCompletion);
      db.SaveChanges();
      return View("SurveyMessage");
    }

    public ActionResult ClientSend()
    {
      return View();
    }

    public ActionResult BreakOut(int blockID, string agent, int cc)
    {
      Guid ccLogon = db.CallCentres.Find(cc).LogOn;
      SurveyCompletion surveyCompletion = new SurveyCompletion(blockID, agent, ccLogon);
      surveyCompletion.Note = "Did not wish to partake in the survey";
      db.SurveyCompletion.Add(surveyCompletion);
      db.SaveChanges();
      return View("SurveyMessage");
    }

    public ActionResult Validate(int blockID)
    {
      LeadStatus leadStatus=db.LeadStatus.Where(m => m.BlockID == blockID && m.PurchaseOrderID == null).FirstOrDefault();
      leadStatus.LeadFlagsID = 2;
      db.Entry(leadStatus).State = EntityState.Modified;
      db.SaveChanges();
      int callCentreID = GetID();
      Guid logon = db.CallCentres.Where(m => m.CallCentreID == callCentreID).FirstOrDefault().LogOn;
      return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fsurveys%2fCallCentreQC&rs:Command=Render&logon=" + logon.ToString());
    }

    public ActionResult Disapprove(int blockID)
    {
      LeadStatus leadStatus=db.LeadStatus.Where(m => m.BlockID == blockID && m.PurchaseOrderID == null).FirstOrDefault();
      leadStatus.LeadFlagsID = 3;
      db.Entry(leadStatus).State = EntityState.Modified;
      db.SaveChanges();
      int callCentreID = GetID();
      Guid logon = db.CallCentres.Where(m => m.CallCentreID == callCentreID).FirstOrDefault().LogOn;
      return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fsurveys%2fCallCentreQC&rs:Command=Render&logon=" + logon.ToString());
    }

    public ActionResult QCLeads()
    {
      int callCentreID = GetID();
      Guid logon = db.CallCentres.Where(m => m.CallCentreID == callCentreID).FirstOrDefault().LogOn;
      return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fsurveys%2fCallCentreQC&rs:Command=Render&logon=" + logon.ToString());
    }

    public ActionResult Tracker()
    {
      int callCentreID = GetID();
      Guid logon = db.CallCentres.Where(m => m.CallCentreID == callCentreID).FirstOrDefault().LogOn;
      return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fsurveys%2fDailyAnalysis&rs:Command=Render&cc=" + logon.ToString());
    }

    public ActionResult Progress()
    {
      int callCentreID = GetID();
      Guid logon = db.CallCentres.Where(m => m.CallCentreID == callCentreID).FirstOrDefault().LogOn;
      return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fsurveys%2fCurrentTracker&rs:Command=Render&cc=" + logon.ToString());
    }

    public ActionResult SuppliedData()
    {
      int callCentreID = GetID();
      Guid logon = db.CallCentres.Where(m => m.CallCentreID == callCentreID).FirstOrDefault().LogOn;
      return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fsurveys%2fExportedData&rs:Command=Render&callcentreid=" + logon.ToString());
    }

    public ActionResult UploadSurveys()
    {
      int ccID = GetID();
      Guid ccLogon = db.CallCentres.Find(ccID).LogOn;
      return RedirectToAction("UploadSurveys", "Operations", new { callCentreID = ccLogon });
    }

    public ActionResult OutputTemplates()
    {
      int callCentreID = GetID();
      Guid logon = db.CallCentres.Where(m => m.CallCentreID == callCentreID).FirstOrDefault().LogOn;
      return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fsurveys%2fOutputTemplate&rs:Command=Render&cc=" + logon.ToString());
    }

    public ActionResult PurchaseOrders()
    {
      int callCentreID = GetID();
      Guid logon = db.CallCentres.Where(m => m.CallCentreID == callCentreID).FirstOrDefault().LogOn;
      return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fsurveys%2fPurchaseOrder&rs:Command=Render&c=" + logon.ToString());
    }
    
    // new method here
  }
}
